require 'rexml/document'
require 'Datos'
require 'MdbException'
require 'pelicula'

class ImportExport
  
  def importar biblio
    doc = REXML::Document.new File.new(biblio)
	root = doc.root
	pelisXdvd = {}
	begin
	  doc.elements.each("Filmoteca/Disco") do |dvds|
	    dvd = ""
	    dvd = dvds.attributes["id"] unless dvds.attributes["id"].nil?
	    pelisXdvd[dvd] = []
	    dvds.elements.each("Pelicula") do |pelicula|
	      peli = Pelicula.new
		  pelicula.elements.each("Titulo") {|title| peli.titulo = title.text.strip}
		  pelicula.elements.each("Fecha") {|year| peli.anno = year.text.to_i}
		  pelicula.elements.each("Director") {|director| peli.director = director.text.strip}
		  pelicula.elements.each("Sinopsis") {|sinopsis| peli.sinopsis = sinopsis.text.strip}

		  pelisXdvd[dvd] << peli
	    end
	  end
      Datos.instance.addPeliculas pelisXdvd
	rescue MdbException => mdbe
	  puts m.message 
	  puts "#{peli.titulo} (#{peli.anno}) de #{peli.director}"
	rescue REXML::ParseException => xmle
	  raise MdbException.new "Error de parseo", xmle
    end
  end

  def exportar fn_salida
    doc = REXML::Document.new
	doc.add_element "Filmoteca"
	Datos.instance.peliculasXdvd().each do |dvd, peliculas|
      dvd_xml = REXML::Element.new "Disco"
	  dvd_xml.add_attribute("id", dvd) unless (dvd.nil? or dvd == "")

	  peliculas.each do |peli|
	    pelicula = REXML::Element.new "Pelicula"
		pelicula.add_element "Titulo"
		pelicula.add_element "Fecha"
		pelicula.add_element "Director"
		pelicula.add_element "Sinopsis"
		pelicula.elements["Titulo"].text = peli.titulo
		pelicula.elements["Fecha"].text = peli.anno
		pelicula.elements["Director"].text = peli.director
		pelicula.elements["Sinopsis"].text = peli.sinopsis

		dvd_xml.add_element pelicula
	  end
	  doc.root.elements << dvd_xml
	end
	doc << REXML::XMLDecl.new
	doc.write(File.new(fn_salida, "w"), 4)
  end
end
